package com.demo.datastructure.linkedList;

/**
 * @author ljr
 * @version 1.0
 * @description: 链表合并的实现
 * @date 2021/10/5 22:18
 */
public class MyLinkedListMergeDemo {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null && l2 == null) return null;
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode head = new ListNode(0, null);
        ListNode prev = head;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                prev.next = l1;
                l1 = l1.next;
            }else{
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
            prev.next = null;
        }

        prev.next = l1 == null ?  l2 : l1;
        ListNode oldHead = head;
        head = head.next;
        oldHead.next = null;
        return head.next;
    }

}
